package service

import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model"
	"gin-luban-server/model/request"
	"gorm.io/gorm"
)

//create
func CreateBasicConfig( configure model.SysBasicConfigure) (err error) {
	if !errors.Is(global.GVA_DB.Where("purpose =  ? AND server_idc = ?", configure.Purpose, configure.ServerIdc).First(&model.SysBasicConfigure{}).Error, gorm.ErrRecordNotFound) {
		return errors.New("存在相同的用途")
	}
	err = global.GVA_DB.Create(&configure).Error
	return err
}



//@author: guo
//@function: GetCmdbServersInfoList
//@description: 分页获取CmdbServers记录
//@param: info request.CmdbServersSearch
//@return: err error, list interface{}, total int64
func GetBasicConfigList(con model.SysBasicConfigure,info request.PageInfo,desc bool) (err error, list interface{}, total int64) {
	limit := info.PageSize
	offset := info.PageSize * (info.Page - 1)
	// 创建db
	db := global.GVA_DB.Model(&model.SysBasicConfigure{})
	var configlist []model.SysBasicConfigure
	// 如果有条件搜索 下方会自动创建搜索语句
	if con.Purpose != "" {
		db = db.Where("purpose = ?",con.Purpose)
	}
	if con.BasicUser != "" {
		db = db.Where("ip_address LIKE ?","%"+ con.BasicUser+"%")
	}

	err = db.Count(&total).Error

	if err != nil {
		return err,configlist, total
	} else {
		db = db.Limit(limit).Offset(offset)
		err = db.Find(&configlist).Error
		//err = db.Preload("Company").Find(&cmdbServerss).Error
	}
	return err, configlist, total
}

//UpdateBasicCon
//update
func UpdateBasicConfig(sysBasicCon model.SysBasicConfigure) (err error) {
	var conf []model.SysBasicConfigure
    err = global.GVA_DB.Where("purpose = ? AND server_idc = ? ",sysBasicCon.Purpose, sysBasicCon.ServerIdc).Not("id = ?",sysBasicCon.ID).Find(&conf).Error
	if len(conf) > 0{
		return errors.New("用途重复")
	}
	err = global.GVA_DB.Where("id = ?", sysBasicCon.ID).First(&model.SysBasicConfigure{}).Updates(&sysBasicCon).Error
	return err
}


func DeleteBasicConfig(BasicConfigureDEL model.SysBasicConfigure) (err error) {
	err = global.GVA_DB.Delete(&BasicConfigureDEL).Error
	return err
}